/**
 * Created by mnooshroom on 2015/7/26 0026.
 *
 * 顶部快捷开始菜单
 *
 */
define('quickStart', ['avalon', '../../package/bill/bill'], function () {
    var vm = avalon.define({
        $id: "quickStart",
        ready: function () {
            console.log("快捷开始准备就绪")
            vm.getReport()
            vm.getStores()
            avalon.scan()
        },
        //绑定快捷键
        $hotKeyList: {
            "f1": function () {
                quickStart.start("sell")
            },
            "f2": function () {
                quickStart.start("sellReturn")
            },
            "f3": function () {
                quickStart.start("pur")
            },
            "f4": function () {
                quickStart.start("purReturn")
            },
            "f5": function () {
                if (confirm("如果刷新浏览器，未保存的操作将丢失，确定要刷新么？")) {
                    window.location.reload()
                }
            },
            //总账记录 Alt+Z
            "alt+z": function () {
                //    window.location.href="#!/all/0"

                window.location.href = "#!/order/0"
            },
            //订单查询 Alt+D
            "Alt+D": function () {
                window.location.href = "#!/search/0"
            },
            //商品管理 Alt+S
            "Alt+S": function () {
                window.location.href = "#!/goods/0"
            },
            //客户供应商 Alt+K
            "Alt+K": function () {
                window.location.href = "#!/customer/0"
            },
            //门店管理 Alt+M
            "Alt+M": function () {
                window.location.href = "#!/store/0"
            },
            //报表中心 Alt +B
            "Alt+B": function () {
                window.location.href = "#!/addUp/0"
            },
            //更多 Alt +G
            "Alt+G": function () {
                window.location.href = "#!/more/0"
            },
            //搜索商品  ctrl+O
            "alt+O": function () {
                window.document.getElementById("searchGoods").focus()
            },
            //搜索客户  ctrl+P
            "alt+P": function () {
                window.document.getElementById("searchCustomer").focus()
            }
            //用来屏蔽backspace键返回之前的页面!!不能屏蔽，如果了，文字的时候就不能回删了！
            //"backspace":function(){}
        },

        binding: false,

        bindBillKey: function () {
            if (!vm.binding) {
                bindK(vm.$hotKeyList)
                vm.binding = true
            }

        },
        removeBillKey: function () {
            if (vm.binding) {
                removeK(vm.$hotKeyList)
                vm.binding = false
            }

        },


        //登录状态
        inSide: false,

        //用户数据
        user: {
            UserName: '',
            uid: ''
        },

        //登出
        logout: function () {
            ws.call({

                i: "User/logout",
                success: function () {

                    quickStart.inSide = false
                    tip.on("已退出登录", 1, 3000)
                    cache.go({
                        "Token": "",
                        "un": "",
                        "uid": "",
                        "HURL": ""
                    })
                    window.location.href = "#!/login"

                }
            })
        },

        //模态框开启,传入不同的参数开启不同的表单的模态框
        preLoad: function (n) {

            require(['text!../../package/bill/bill.html'], function (html) {
            })
        },
        unLoad: function () {
            vm.loaded = false
        },
        loaded: false,
        start: function (n) {
            if(window.location.hash=='#!/bill/'+n){
                //就是当前郁闷
                bill.ready(n)
            }else{
                window.location.href="#!/bill/"+n
            }

        },

        /*控制搜索*/
        searching: 0,
        $goodsHotKey: {
            $opt: {
                type: "keydown"
            },
            "up": function () {
                if (vm.focusGoods > 0) {
                    vm.focusGoods--
                }
                else {
                    vm.focusGoods = vm.goods.length - 1
                }
            },
            "down": function () {
                if (vm.focusGoods < vm.goods.length - 1) {
                    vm.focusGoods++
                }
                else {
                    vm.focusGoods = 0
                }
            },
            'left': function () {
                if (vm.GP > 1) {
                    vm.pagerGoods(1)
                }

            },
            "right": function () {
                if (vm.GP < (Math.ceil(vm.GT / vm.GN)))
                    vm.pagerGoods(-1)
            },
            'enter': function () {
                if (vm.focusGoods != -1) {
                    vm.jump2Goods(vm.focusGoods)
                }
            }
        },

        focus: function (i) {
            vm.searching = i
            if (i == 1) {
                removeK(vm.$cusHotKey)
                //todo 聚焦的是商品,绑定关于商品搜索的快捷键
                bindK(vm.$goodsHotKey)

            }
            else if (i == 2) {
                removeK(vm.$goodsHotKey)
                //todo 聚焦的是客户,绑定关于客户搜索的快捷键
                bindK(vm.$cusHotKey)
            }
        },
        blur: function () {
            //todo 快捷键解绑定
            removeK(vm.$goodsHotKey)
            removeK(vm.$cusHotKey)
            vm.searching = 0
            setTimeout(function () {
                vm.goods = []
                vm.customer = []
            }, 400)

        },
        // 商品搜索
        goodsWaiting: false,
        goods: [],
        goodsKey: "",
        goLastKey: "",
        focusGoods: -1,
        onGoods: false,
        goHover: function (i) {
            vm.onGoods = i

        },
        goOut: function (i) {
            vm.onGoods = 0
        },
//        lastInput:0,
        GP: 1,
        GT: 0,
        GN: 8,
        /*为判断条码创造的变量*/
        lastTime: 0,      //上次改变时间
        timeArr: [],     //每两次改变的时间差
        searchTimeOut: 0,
        thatIsTM: false,       //是否为条形码
        searchGoods: function () {
            /*****获得时间差*****/
            if (vm.lastTime > 0) {
                var tempD = new Date();
                vm.timeArr.push(tempD - vm.lastTime);
            }
            vm.lastTime = new Date();
            if (vm.searchTimeOut != 0) {
                clearTimeout(vm.searchTimeOut);
            }
            vm.searchTimeOut = setTimeout(function () {
                /*****算平均值********/
                var sum = 0;
                for (var i = 0; i < vm.timeArr.length; i++) {
                    sum += vm.timeArr[i];
                }
                var avg = sum / vm.timeArr.length;
                if (avg < 10) {
                    vm.thatIsTM = true;
                } else {
                    vm.thatIsTM = false;
                }
                /*****原来的搜索逻辑*****/
                if (vm.goodsKey != "" && vm.goodsKey != vm.goLastKey) {
                    //触发请求
                    vm.goLastKey = vm.goodsKey;
                    vm.GP = 1;
                    listen(vm.callGoods);
                } else if (vm.goodsKey == "" && vm.goodsKey != vm.goLastKey) {
                    vm.goReset();
                }
                /**********************/
            }, 25);
            /*****重置*****/
            if (vm.goodsKey == '' && vm.goLastKey != '') {
                vm.lastTime = 0;      //上次改变时间
                vm.timeArr = [];     //每两次改变的时间差
                vm.searchTimeOut = 0;
                vm.thatIsTM = false;       //是否为条形码
            }
        },
        $waiting: false,
        $waitTime: 2,
        pagerGoods: function (n) {
            var newGP = vm.GP + -n;
            if (newGP >= 1) {
                vm.GP = newGP
            }
            else {
                vm.GP = 1
            }
            listen(vm.callGoods)
        },
        //正是召唤商品列表
        callGoods: function () {
            vm.goodsWaiting = true
            if (vm.GP < 1) {
                vm.GP = 1
            }
            ws.call({
                i: "Goods/search",
                data: {
                    keyword: vm.goodsKey,
                    P: vm.GP,
                    N: vm.GN
                },
                success: function (res) {

                    if (vm.GP == res.P) {
                        if (res.L.length && vm.goodsKey != '') {
                            //vm.GP = res.P
                            /***判断是否为条形码***/
                            if (res.L.length == 1) {
                                if (vm.thatIsTM) {
                                    vm.goodsKey = '';
                                    vm.lastTime = 0;      //上次改变时间
                                    vm.timeArr = [];     //每两次改变的时间差
                                    vm.searchTimeOut = 0;
                                    vm.thatIsTM = false;       //是否为条形码
                                    window.location.href = "#!/goodsInfo/" + res.L[0].GoodsID;
                                    return;
                                }
                            }

                            var list = []
                            var resL = res.L
                            var len = resL.length

                            for (var i = 0; i < len; i++) {

                                var All = 0;
                                //当前库房获取逻辑,

                                if (resL[i].Store) {
                                    for (var o = 0; o < resL[i].Store.length; o++) {
                                        if (resL[i].Store[o].StoreID == vm.nowStore.StoreID) {
                                            All = resL[i].Store[o].Amount
                                            break
                                        }
                                    }
                                }


                                var go = {
                                    GoodsID: resL[i].GoodsID,
                                    Name: resL[i].Name,
                                    ThisTotle: All,
                                    AllTotle: resL[i].StoreTotal,
                                    Price1: resL[i].Price1,
                                    Price0: resL[i].Price0,
                                    BarCode: resL[i].BarCode
                                }
                                list.push(go)


                            }
                            vm.goods = list
                        } else {
                            vm.goods = []
                            //vm.GP--

                        }
                        vm.GT = res.T
                    }
                    vm.goodsWaiting = false


                }
            })
        },
        //选中商品
        selectGoods: function (index) {
            vm.focusGoods = index
        },
        //跳转商品详情
        jump2Goods: function (index) {
            var GoodsID = vm.goods[index].GoodsID
            window.location.href = "#!/goodsInfo/" + GoodsID
        },
        goReset: function () {
            vm.goods = []
            vm.GP = 1
            vm.GT = 0
            vm.goodsKey = ""
            vm.goLastKey = ""
            vm.focusGoods = -1
            vm.onGoods = false
            vm.goodsWaiting = false
        },

        //客户搜索
        $cusHotKey: {
            "up": function () {
                if (vm.focusCustomer > 0) {
                    vm.focusCustomer--
                }
                else {
                    vm.focusCustomer = vm.customer.length - 1
                }
            },
            "down": function () {
                if (vm.focusCustomer < vm.customer.length - 1) {
                    vm.focusCustomer++
                }
                else {
                    vm.focusCustomer = 0
                }
            },
            'left': function () {
                if (vm.CP > 1) {
                    vm.pagerCus(1)
                }

            },
            "right": function () {
                if (vm.CP < (Math.ceil(vm.CT / vm.CN))) {
                    vm.pagerCus(-1)
                }
            },
            'enter': function () {
                if (vm.focusCustomer != -1) {
                    vm.jump2Customer(vm.focusCustomer)
                }
            }
        },
        customerWaiting: false,
        customer: [],
        customerKey: "",
        cusLastKey: "",
        focusCustomer: -1,
//        搜索客户
        searchCustomer: function () {

            if (vm.customerKey != "" && vm.customerKey != vm.cusLastKey) {
                //触发请求
                vm.cusLastKey = vm.customerKey
                vm.CP = 1;
                vm.callCus()

            }
            else if (vm.customerKey == "" && vm.customerKey != vm.cusLastKey) {
                vm.cuReset()
            }
        },
        CP: 1,
        CT: 0,
        CN: 8,
        pagerCus: function (n) {
            var newCP = vm.CP + -n;
            if (newCP >= 1) {
                vm.CP = newCP
            }
            else {
                vm.CP = 1
            }

            listen(vm.callCus)


        },
        callCus: function () {
            vm.customerWaiting = true
            if (vm.CP < 1) {
                vm.CP = 1
            }
            ws.call({
                i: "Customer/search",
                data: {
                    keyword: vm.customerKey,
                    P: vm.CP,
                    N: vm.CN
                },
                success: function (res) {
                    if (vm.CP == res.P) {
                        if (res.L.length && vm.customerKey != '') {
//                            var list=[]
                            var resL = res.L
//                            var len=resL.length
//                            for(var i=0;i<len;i++){
//
//                                //插入数组
//                                list.push(resL[i])
//
//
//                            }
                            vm.customer = resL


                            vm.CP = res.P

                        }
                        else {
                            vm.customer = []
                            //vm.CP--

                        }
                        vm.CT = res.T

                    }
                    vm.customerWaiting = false

                }
            })
        },
        selectCustomer: function (index) {
            vm.focusCustomer = index
        },

        //跳转客户详情
        jump2Customer: function (index) {
            var CustomerID = vm.customer[index].CustomerID
            window.location.href = "#!/customerInfo/" + CustomerID

        },
        cuReset: function () {
            vm.customer = []
            vm.CP = 1
            vm.CT = 0
            vm.customerKey = ""
            vm.cusLastKey = ""
            vm.focusCustomer = -1
            vm.onGoods = false
            vm.customerWaiting = false
        },

        /*库房*/
        Stores: [],
        nowStore: {},

        //获取库房
        getStores: function () {
            ws.call({
                i: "Store/get",
                data: {
                    StoreIDs: []
                },
                success: function (res) {
                    if (res.length === 0) {
                        //还没有创建店铺
                        var p = confirm("您还没有创建任何的门店，将无法创建订单，\n是否现在就去添加？")
                        if (p) {
                            window.location.href = "#!/store/0"
                        }
                    }
                    else {
                        if (!res.err) {
                            vm.Stores=[]
                            for (var i = 0; i < res.length; i++) {

                                vm.Stores.push(res[i])
                            }


                            //加载上次所在的库房
                            var lastStore = cache.go("store")
                            if (lastStore < res.length) {
                                vm.changeStore(lastStore)
                            } else {
                                vm.changeStore(1)
                            }
                        }
                        else {
                            console.log(res)
                        }
                    }

                }
            })
        },

        //库房切换
        showMoreStore: false,
        moreStore: function () {
            vm.showMoreStore = true
        },
        closeMoreS: function () {
            vm.showMoreStore = false
        },
        changeStore: function (index) {
            var index = Number(index)
            vm.nowStore = vm.Stores[index]
            vm.closeMoreS()
            if (window.bill) {
                bill.Store = vm.Stores[index]
            }
            if (window.goods) {
                goods.buildStore()
            }

            //记录本次变更的库房
            cache.go({
                store: index
            })
        },

        /*******************全局统计***********************/
        Report: {
            "Today": {
                "Sale": 0
            },
            "Month": {
                "Sale": 0
            },
            "Overdue": {
                "Receive": 0,
                "Pay": 0
            }
        },
        getReport: function () {
            if (vm.inSide) {
                ws.call({
                    i: "Report/now",
                    data: {},
                    success: function (res) {
                        if (res) {
                            vm.Report = res
                        }
                        else {
                            console.log(res)
                        }
                    }
                })
            } else {
                setTimeout(function () {
                    vm.getReport()
                }, 1000)
            }

        },

        showGlobal: false,
        wShowGlobal: false,
        lookGlobal: function () {
            if (vm.showGlobal) {
                vm.showGlobal = false;
                vm.wShowGlobal = false;
            } else {
                vm.showGlobal = true;
                setTimeout(function () {
                    vm.wShowGlobal = true;
                }, 200);
            }
        },

        /*控制 备选商品列表 更多订单按钮的出现于消失*/
        showMoreBill: false,
        toggleBill: function () {
            vm.showMoreBill = !vm.showMoreBill;
        }


    })
    return quickStart = vm
})
